package com.ciaojian.core.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 使用token验证用户是否登录
 *
 * @author Atlakyn
 **/
public class TokenUtil {
    //token秘钥
    private static final String TOKEN_SECRET = getId();

    //生成UUID
    private static String getId() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    //生成token
    public static String makeToken(String openid) {
        String token = "";
        try {
            //秘钥及HMAC256加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String, Object> header = new HashMap<>();
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            //携带username，password信息，生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("openid", openid)
                    .sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return token;
    }

    /**
     * 验证token，通过返回true
     *
     * @param token 需要校验的串
     **/
    public static boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    //获取token里携带的信息（厂商id）
    public static String getUserOpenid(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("openid").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    //获取token里携带的信息（userId）
    public static Integer getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("id").asInt();

        } catch (JWTDecodeException e) {
            return null;
        }
    }

}

